import { createRouter, createWebHistory } from 'vue-router';
import { nextTick } from 'vue'; // 新增这行
import { useUserStore } from '@/stores/user';
import { staticRoutes, layoutRoute } from './routes';
import http from '@/utils/request';
import { usePermissionStore } from '@/stores/permission';

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front'];


router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 小花在线图书馆`;
  } else {
    document.title = '小花在线图书馆';
  }

  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  console.log('[导航守卫] 开始处理路由:', `从 ${from.path} 到 ${to.path}`);

  // 精确白名单检查（修复点1）
  if (whiteList.includes(to.path)) {
    console.log(`[白名单] 路径 ${to.path} 精确匹配，直接放行`);
    next();
    return;
  }

  // 简化未登录检查（修复点2）
  if (!userStore.library_token) {
    console.warn(`[未登录] 访问受保护路径 ${to.path}，跳转登录页`);
    next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    return;
  }

  // 已登录处理逻辑
  if (userStore.library_token) {
    // 用户信息获取模块
    if (!userStore.library_users.roles.length) {
      console.log('[用户信息] 开始获取用户角色信息');
      try {
        const infoRes = await http.get('/user/getInfo');
        console.log('[用户信息] 获取成功，角色数据:', infoRes.data.roles);
        userStore.roles = infoRes.data.roles;
      } catch (error) {
        console.error('[用户信息] 获取失败:', error);
        userStore.logout();
        next('/login');
        return;
      }
    }

    // 动态路由处理模块
    if (userStore.roles.length && !permissionStore.hasGenerated) {
      console.log('[动态路由] 开始生成动态路由');
      await permissionStore.generateRoutes(userStore.roles);

      console.log('[路由清理] 开始清除旧路由');
      permissionStore.routes.forEach(route => {
        if (router.hasRoute(route.name)) {
          console.log(`[路由清理] 移除路由: ${route.name}`);
          router.removeRoute(route.name);
        }
      });

      console.log('[路由注入] 开始添加新路由');
      permissionStore.routes.forEach(route => {
        console.log(`[路由注入] 添加路由: ${route.name}`);
        router.addRoute('layoutRoute', {
          ...route,
          path: route.path.startsWith('/') ? route.path.slice(1) : route.path
        });
      });

      permissionStore.setHasGenerated(true);
      console.log('[动态路由] 路由生成完成，执行强制导航');

      const redirectPath = to.redirectedFrom?.path || '/dashboard/index';
      console.log(`[重定向] 目标路径: ${redirectPath}`);
      next({ path: redirectPath, replace: true, query: to.query, hash: to.hash });
      return;
    }

    // 登录页重定向（修复点3）
    if (to.path === '/login') {
      console.log('[重定向] 已登录用户禁止访问登录页');
      next({ path: '/dashboard/index', replace: true });
      return;
    }
  }

  console.log('[导航守卫] 所有检查通过，正常放行');
  next();
});


export { router };
export default router;


